package com.huping.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.huping.mapper.*;
import com.huping.pojo.*;
import com.huping.service.HomeworkService;
import com.huping.utils.AliOSSUtils;
import com.huping.utils.compare.CodeCompare;
import com.huping.utils.compare.Compare;
import com.huping.utils.compare.CosineUtil;
import com.huping.utils.hupingAlgorithm;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Service
public class HomeworkServiceImpl implements HomeworkService {

    @Autowired
    private HomeworkMapper homeworkMapper;
    @Autowired
    private AliOSSUtils aliOSSUtils;
    @Autowired
    private GradeMapper gradeMapper;
    @Autowired
    private TcMapper tcMapper;
    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private SampleCaseMapper sampleCaseMapper;
    @Autowired
    private ScoreRecordMapper scoreRecordMapper;

    @Autowired
    private SerializeConfig serializeConfig;




    @Override
    public Result details(JSONObject param) {
        int homeworkId = Integer.parseInt(param.getString("homeworkId"));
        Homework homeworkDetail = homeworkMapper.getHomeworkDetail(homeworkId);
        if (homeworkDetail == null)
            return Result.error("未查询到作业详细信息");
        else {
            JSONObject gradeJSON = (JSONObject) JSONObject.toJSON(homeworkDetail,serializeConfig);
            JSONArray filesArray = JSON.parseArray(homeworkDetail.getFile());
            gradeJSON.put("file", filesArray);

            //获取编程作业的样例输入输出
            List<SampleCase> sampleCaseList = sampleCaseMapper.sampleCaseSelectByHomeworkId(homeworkId);
            JSONArray sampleCaseJSONArray = JSON.parseArray(JSONObject.toJSONString(sampleCaseList));
            gradeJSON.put("sampleCase", sampleCaseJSONArray);

            return Result.success(gradeJSON);
        }

    }


    @Override
    public Result teacherCreate(Homework homework, Claims claims) {
        homework.setTeacherId((String) claims.get("userid"));
        int r = homeworkMapper.homeworkInsert(homework);
        if (r == 1) return Result.success();
        else return Result.error("创建作业失败");
    }

    @Override
    public PageBean homeworkSelect(Claims claims, JSONObject param) {



        String userid = (String) claims.get("userid");
        String kind = (String) claims.get("kind");
        //  int homeworkId=Integer.parseInt(param.getString("homeworkId"));
        String homeworkId = param.getString("homeworkId");

        String courseId = param.getString("courseId");
        String homeworkName = param.getString("homeworkName");
        String courseName = param.getString("courseName");


        String teacher = param.getString("teacher");


        if (kind.equals("2")) {
            PageHelper.startPage(Integer.parseInt(param.getString("page")), Integer.parseInt(param.getString("size")));
            List<Map<String, Object>> r = homeworkMapper.teacherHomeworkSelect(userid, courseId, courseName, homeworkName);
            Page<Map<String, Object>> p = (Page<Map<String, Object>>) r;
            PageBean pageBean = new PageBean(p.getTotal(), p.getResult());
            return pageBean;
        } else {
            PageHelper.startPage(Integer.parseInt(param.getString("page")), Integer.parseInt(param.getString("size")));
            List<Map<String, Object>> r = homeworkMapper.studentHomeworkSelect(userid, courseId, courseName, homeworkName, teacher);
            Page<Map<String, Object>> p = (Page<Map<String, Object>>) r;
            PageBean pageBean = new PageBean(p.getTotal(), p.getResult());
            return pageBean;
        }

    }

    @Override
    public Result teacherAnnex(Integer homeworkId, List<MultipartFile> files) {

        String fileListStr = homeworkMapper.getHomeworkFile(homeworkId);
        List<Annex> fileList = JSON.parseArray(fileListStr, Annex.class);


        files.forEach((file) -> {

            String url;
            try {
                url = aliOSSUtils.upload(file);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            String fileName = file.getOriginalFilename();
            fileList.add(new Annex(fileName, url));

        });


        String json = JSON.toJSONString(fileList);
        int r = homeworkMapper.updateHomeworkFile(homeworkId, json);
        if (r == 1) return Result.success();
        else return Result.error("上传附件失败");

    }

    @Override
    public Result teacherUpdate(Homework homework) {
        int r = homeworkMapper.homeworkUpdate(homework);
        if (r == 1) return Result.success();
        else return Result.error("更新课程失败");
    }

    @Override
    public Result submitDetails(Integer homeworkId, Claims claims) {

        String userid = (String) claims.get("userid");
        Integer scoreTeacher = gradeMapper.getStudentScoreTeacher(userid, homeworkId);

        List<Map<String, Object>> list = scoreRecordMapper.getAllScoreRecord(userid, homeworkId);//没有互评记录就只看老师的
        Integer scoreTotal;
        if (list.isEmpty()) {
            scoreTotal  = scoreTeacher;
        } else {
            List<Integer> newList = new ArrayList<>();
            for (Map<String, Object> map : list) {
                newList.add((Integer) map.get("score"));
            }
            Integer[] hupingArrInteger = newList.toArray(new Integer[0]);
            int[] hupingArray = new int[hupingArrInteger.length];

            for (int i = 0; i < hupingArrInteger.length; i++) {
                hupingArray[i] = hupingArrInteger[i]; // 自动拆箱
            }

            int scoreHuping = hupingAlgorithm.getScoreHuping(hupingArray);
            gradeMapper.setScoreHuping(userid, homeworkId, scoreHuping);

             scoreTotal = (int) (scoreHuping * 0.3 + scoreTeacher * 0.7);
        }
        gradeMapper.setScoreTotal(userid, homeworkId, scoreTotal);



        Map<String, Object> gradeResult = gradeMapper.getGradeDetails(homeworkId, userid);
        if (gradeResult == null) {
            gradeMapper.gradeInsert(userid, homeworkId);
            gradeResult = gradeMapper.getGradeDetails(homeworkId, userid);
        }
        JSONObject gradeJSON = (JSONObject) JSONObject.toJSON(gradeResult);
        JSONArray filesArray = JSON.parseArray((String) gradeResult.get("file"));
        gradeJSON.put("file", filesArray);

        //获取编程作业的样例输入输出
        List<SampleCase> sampleCaseList = sampleCaseMapper.sampleCaseSelectByHomeworkId(homeworkId);
        JSONArray sampleCaseJSONArray = JSON.parseArray(JSONObject.toJSONString(sampleCaseList));
        gradeJSON.put("sampleCase", sampleCaseJSONArray);

        return Result.success(gradeJSON);
    }

    @Override
    public Result studentUpdate(Grade grade) {
        int r = gradeMapper.updateGradeContent(grade);
        if (r == 1) return Result.success();
        else return Result.error("更新失败");
    }

    @Override
    public Result studentAnnex(Integer gradeId, List<MultipartFile> files) {
        String fileListStr = gradeMapper.getGradeFile(gradeId);
        List<Annex> fileList = JSON.parseArray(fileListStr, Annex.class);

        files.forEach((file) -> {
            String url;
            try {
                url = aliOSSUtils.upload(file);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            String fileName = file.getOriginalFilename();
            fileList.add(new Annex(fileName, url));
        });

        String json = JSON.toJSONString(fileList);
        int r = gradeMapper.updateGradeFile(gradeId, json);
        if (r == 1) return Result.success();
        else return Result.error("上传附件失败");
    }

    @Override
    public Result teacherSelectAllCourse(String userid) {
        List<Map<String, Object>> resultList = tcMapper.teacherSelectAllCourse(userid);
        if (!resultList.isEmpty()) return Result.success(resultList);
        else return Result.error("查询教师所授课程失败");
    }

    @Override
    public Result teacherAnnexDelete(Integer homeworkId, String url) {
        String fileListStr = homeworkMapper.getHomeworkFile(homeworkId);
        List<Annex> fileList = JSON.parseArray(fileListStr, Annex.class);
        fileList.removeIf(annex -> annex.getUrl().equals(url));

        String json = JSON.toJSONString(fileList);
        int r = homeworkMapper.updateHomeworkFile(homeworkId, json);
        if (r == 1) return Result.success();
        else return Result.error("删除附件失败");
    }

    @Override
    public Result studentAnnexDelete(Integer gradeId, String url) {
        String fileListStr = gradeMapper.getGradeFile(gradeId);
        List<Annex> fileList = JSON.parseArray(fileListStr, Annex.class);
        fileList.removeIf(annex -> annex.getUrl().equals(url));

        String json = JSON.toJSONString(fileList);
        int r = gradeMapper.updateGradeFile(gradeId, json);
        if (r == 1) return Result.success();
        else return Result.error("删除附件失败");
    }

    @Override
    public  Result teacherGetAllHomework(String userid,JSONObject param){


      List<Map<String,Object>> list=homeworkMapper.teacherGetAllHomework(userid,param.getString("courseId"));
        for (Map<String,Object> homework :list ) {
            String fileString = (String) homework.get("file");
            JSONArray filesArray = JSON.parseArray(fileString);
            homework.put("file", filesArray);
        }
     return  Result.success(list);
    }


    @Override
    public Result checkSimilarity(Integer homeworkId) {
        String similarityJSONStr = homeworkMapper.getSimilarityByHomeworkId(homeworkId);
        if(similarityJSONStr!=null){
            JSONArray similarityJSONArray = JSON.parseArray(similarityJSONStr);
            return Result.success(similarityJSONArray);
        }
        else{
            String homeworkType =homeworkMapper.getHomeworkTypeByHomeworkId(homeworkId);
            List<Map<String,Object>> resultList = new ArrayList<>();
            //普通作业
            if(homeworkType.equals("0")){
                List<Map<String,String>> contentsList=gradeMapper.getAllContentByHomeworkId(homeworkId);
                CosineUtil cosineUtil=new CosineUtil();
                for(int i=0;i<contentsList.size();i++){
                    for(int j=i+1;j<contentsList.size();j++){
                        double similarity=cosineUtil.calculateCosine(contentsList.get(i).get("content"),contentsList.get(j).get("content"));
                        Map<String,Object> r = new HashMap<>();
                        r.put("studentA",contentsList.get(i).get("student_id"));
                        r.put("studentB",contentsList.get(j).get("student_id"));
                        r.put("similarity",similarity);
                        resultList.add(r);
                    }
                }
            }//程序作业
            else{
                CodeCompare codeCompare=new CodeCompare();

                List<Map<String,String>> codeList=gradeMapper.getAllCodeByHomeworkId(homeworkId);
                System.out.println(codeList);
                for(int i=0;i<codeList.size();i++){
                    for(int j=i+1;j<codeList.size();j++){
                        String codeA=codeList.get(i).get("code");
                        String codeB=codeList.get(j).get("code");
                        codeA = codeCompare.delVariables(codeA);
                        codeB = codeCompare.delVariables(codeB);
                        double similarity=codeCompare.getSimilarity(codeA,codeB);
                        Map<String,Object> r = new HashMap<>();
                        r.put("studentA",codeList.get(i).get("student_id"));
                        r.put("studentB",codeList.get(j).get("student_id"));
                        r.put("similarity",similarity);
                        resultList.add(r);
                    }
                }

            }
            Collections.sort(resultList, new Comparator<Map<String, Object>>() {
                @Override
                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                    // 获取两个Map中的"similarity"值并比较
                    Double similarity1 = (Double) o1.get("similarity");
                    Double similarity2 = (Double) o2.get("similarity");
                    return Double.compare(similarity2, similarity1); // 降序排序
                }
            });

            for (Map<String, Object> map : resultList) {
                System.out.println("StudentA: "+map.get("studentA")+" StudentB: "+map.get("studentB")+" similarity: " + map.get("similarity"));
            }

            String resultJSONStr= JSON.toJSONString(resultList);
            homeworkMapper.updateSimilarity(resultJSONStr,homeworkId);
            return Result.success(resultList);
        }

    }

}
